﻿using aspNetCURD.Database;
using aspNetCURD.Models;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;

namespace aspNetCURD.Services
{
    public class CourseRepository : ICourseRepository
    {
        private readonly AppDbContext _context;
        public CourseRepository(AppDbContext context)
        {
            _context = context;
        }

        public IEnumerable<course> GetCourses(string keyword, int pageIndex, int pageSize)
        {
            int skip = (pageIndex - 1) * pageSize;
            if (!string.IsNullOrEmpty(keyword))
            {
                keyword = keyword.Trim();
                return _context.course.Where(n =>
                    n.cno.Contains(keyword) ||
                    n.cname.Contains(keyword)
                    ).Skip(skip).Take(pageSize).ToList();
            }
            return _context.course.Skip(skip).Take(pageSize).ToList();
        }

        public int GetCourseCount(string keyword)
        {
            if (!string.IsNullOrEmpty(keyword))
            {
                keyword = keyword.Trim();
                return _context.course.Where(n =>
                    n.cno.Contains(keyword) ||
                n.cname.Contains(keyword)).ToList().Count();
            }
            return _context.course.ToList().Count();
        }

        public course GetCourse(string cno)
        {
            return _context.course.Where(n => n.cno.Trim() == cno).FirstOrDefault();
        }

        public void AddCourse(course courseMod)
        {
            _context.course.Add(courseMod);
        }

        public bool Sava()
        {
            return (_context.SaveChanges() >= 0);
        }
    }
}
